package com.chexiehui.jc.ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.aries.ui.view.radius.RadiusRadioButton;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.ChooseStatusModel;
import com.chexiehui.jc.entity.ForumInfo;
import com.chexiehui.jc.event.CreateForumEvent;
import com.chexiehui.jc.mvp.mine.MyForumListCovenant;
import com.chexiehui.jc.mvp.mine.MyForumListPresenter;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.LoadingLayout;
import com.nex3z.flowlayout.FlowLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 我的论坛列表
 */
public class MyForumListActivity extends BaseMvpActivity<MyForumListPresenter> implements MyForumListCovenant.View, View.OnClickListener {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.fl_follow_tip)
    FlowLayout flFollowTip;
    private List<ForumInfo> listData;
    private CommonAdapter<ForumInfo> listAdapter;
    private BasePage<ForumInfo> page;
    private List<ChooseStatusModel> statusModelList;
    private int chooseIndex;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void beforeSetView() {
        statusModelList = new ArrayList<>();
        statusModelList.add(new ChooseStatusModel("全部", ""));
        statusModelList.add(new ChooseStatusModel("已审核", "1"));
        statusModelList.add(new ChooseStatusModel("审核中", "0"));
        statusModelList.add(new ChooseStatusModel("已驳回", "2"));
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("申请的论坛")
                .setDividerVisible(false);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_my_forum_list;
    }

    @Override
    protected void initView(Bundle var1) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        loadingLayout.setOnReloadListener(v -> {
            refreshLayout.finishRefresh(false);
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        });
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (loadingLayout.getStatus() == LoadingLayout.Loading) {
                    refreshLayout.finishRefresh(false);
                    return;
                }
                mvpPresenter.getList(1);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > listData.size()) {
                    mvpPresenter.getList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        recycler.setLayoutManager(new LinearLayoutManager(mContext));

        listData = new ArrayList<>();
        listAdapter = new CommonAdapter<ForumInfo>(mContext, R.layout.item_my_forum, listData) {
            @Override
            protected void convert(ViewHolder holder, ForumInfo item, int position) {
                GlideUtil.loadImageViewCrop(mContext, item.getIcon(), holder.getView(R.id.iv_item_image),
                        R.drawable.shape_square, R.drawable.shape_square);
                holder.setText(R.id.tv_item_name, item.getName());
                holder.setText(R.id.tv_item_desc, item.getIntroduction());
                holder.setText(R.id.tv_item_count, item.getFollowcount() + "车友");
                holder.setText(R.id.rtv_item_status, item.getStatusStr());
            }
        };
        listAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (NoDoubleClickUtils.isDoubleClick()) return;
                startActivity(ForumEditActivity.class,
                        new BundleBuilder().putSerializable("entity", listData.get(position))
                                .create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        recycler.setAdapter(listAdapter);
        setStatusTag();
    }

    private void setStatusTag() {
        flFollowTip.removeAllViews();
        for (int i = 0; i < statusModelList.size(); i++) {
            RadiusRadioButton radiusTextView = (RadiusRadioButton) View.inflate(mContext, R.layout.item_only_car_type3, null);
            radiusTextView.setTag(i);
            radiusTextView.setText(statusModelList.get(i).getName());
            radiusTextView.setOnClickListener(this);
            radiusTextView.setSelected(chooseIndex == i);
            flFollowTip.addView(radiusTextView);
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.finishRefresh(false);
        mvpPresenter.getList(1);
    }

    @Override
    protected MyForumListPresenter createPresenter() {
        return new MyForumListPresenter(this);
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<ForumInfo>> successResult) {
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= listAdapter.getDatas().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (listAdapter.getDatas().size() > 0) {
                    listAdapter.getDatas().clear();
                    listAdapter.notifyDataSetChanged();
                }
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (listAdapter.getDatas().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }

    @Override
    public String getForumStatus() {
        return statusModelList.get(chooseIndex).getStatus();
    }

    @Override
    public void onClick(View v) {
        if (v.getTag() != null) {
            Integer i = (Integer) v.getTag();
            chooseIndex = i;
            setStatusTag();
        }
    }

    @Subscribe
    public void onCreateForumEvent(CreateForumEvent event){
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.finishRefresh(false);
        mvpPresenter.getList(1);
    }

    @OnClick({R.id.fab_send_button})
    public void onViewClicked(View view){
        switch (view.getId()){
            case R.id.fab_send_button:
                startActivityAnimBottom(ForumCreateActivity.class, new BundleBuilder()
                        .putBoolean("isFinishToBottom", true).create());
                break;
        }
    }
}
